package com.dqx.opengl_es_demo.model.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 创建纹理的工具类
 */
public class TextureUtil {
    /**
     * 获取纹理信息，并返回纹理id
     *
     * @param context
     * @param drawableId 图片资源id
     * @return
     */
    public static int getTextureIdByDrawableId(Context context, int drawableId) {
        //通过输入流加载图片
        InputStream is = context.getResources().openRawResource(drawableId);
        Bitmap bitmapTmp;
        try {
            bitmapTmp = BitmapFactory.decodeStream(is);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //装载纹理id的数组
        int[] textures = new int[1];
        //创建空的纹理对象
        GLES20.glGenTextures(1, textures, 0);
        int textureId = textures[0];
        //绑定纹理id
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
        //纹理过滤设置
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);
        //根据图片生成2D纹理
        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, GLUtils.getInternalFormat(bitmapTmp), bitmapTmp, GLUtils.getType(bitmapTmp), 0);
        //释放资源
        //if (!bitmapTmp.isRecycled())
        //    bitmapTmp.recycle();
        return textureId;
    }

    /**
     * 获取纹理信息，并返回纹理id
     *
     * @param bmp 位图
     * @return
     */
    public static int getTextureIdByBitmap(Bitmap bmp) {
        //装载纹理id的数组
        int[] textures = new int[1];
        //创建空的纹理对象
        GLES20.glGenTextures(1, textures, 0);
        int textureId = textures[0];
        //绑定纹理id
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
        //纹理过滤设置
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
        //根据图片生成2D纹理
        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bmp, 0);
        //释放资源
        //if (!bmp.isRecycled())
        //    bmp.recycle();
        return textureId;
    }

}
